<?php

	/**
	 * Product Item
	 *
	 * @author anton.perkin
	 * @version 1.0
	 *
	 */
	class ProductItem
	{
		
		/* VARIABLES */
		
		/**
		 * Product id (from source)
		 *
		 * @var int
		 */
		public $id;
		
		/**
		 * Product id (internal, from DB)
		 *
		 * @var int
		 */
		public $internalId;
		
		/**
		 * Product name
		 *
		 * @var string
		 */
		public $name;

		/**
		 * Product brand
		 *
		 * @var string
		 */
		public $brand;
		
		/**
		 * Product URL
		 *
		 * @var string
		 */
		public $url;
		
		/**
		 * Product URL id (from DB)
		 *
		 * @var string
		 */
		public $urlId;

		/**
		 * Product category id
		 *
		 * @var string
		 */
		public $categoryId;
		
		/**
		 * Product specification page contents
		 *
		 * @var string
		 */
		public $specsPage;
		
		/**
		 * Product main page contents
		 *
		 * @var string
		 */
		public $modelPage;
		
		/**
		 * Images' URLs array
		 *
		 * @var array
		 */
		public $images = array();		
		
		/**
		 * Producy attributes
		 *
		 * @var array
		 */
		public $attributes = array();
		
		
		/* METHODS */
		
		/**
		 * Saves ProductItem into database
		 *
		 */
		public function Save()
		{
			if (DB::ExecuteSQL("
				INSERT INTO t_products
				(
					product_public_id,
					product_name,
					product_url,
					product_url_id
				)
				VALUES
				(
					$this->id,
					'".addslashes(iconv('utf-8', 'cp1251', $this->name))."',
					'$this->url',
					$this->urlId
				);
			") === true)
			{
				//save images to DB
				$this->SaveImages();
				
				//save model page content
				$bookInfoFile = fopen($_SERVER['DOCUMENT_ROOT'].'/yandex/results/products/'.$this->id.'.html', 'w+');
				fwrite($bookInfoFile, $this->modelPage);

				//save specs page content
				$bookInfoFile = fopen($_SERVER['DOCUMENT_ROOT'].'/yandex/results/products/'.$this->id.'_specs.html', 'w+');
				fwrite($bookInfoFile, $this->specsPage);
				
				$this->Log(true);
				$result = true;
			}	
			else 
			{
				$this->Log(false);
				$result = false;
			}
			
			return $result;
		}
		
		/**
		 * Saves ProductItem etails into database
		 *
		 */
		public function SaveDetails()
		{
			$result['success'] = 0;
			$result['fail'] = 0;
			
			//update product info
			DB::ExecuteSQL("
				UPDATE t_products
				SET
					product_brand = '".$this->brand."'
				WHERE
					product_id = ".$this->internalId."
			");				
			
			//save all attributes + attribute categories + values
			foreach($this->attributes as $attributeCategory => $attributes)
			{				
				//attribute categories insert
				$category = DB::ListItems("SELECT attribute_category_id as id FROM t_attribute_categories WHERE attribute_category_name = '{$attributeCategory}' AND category_id = {$this->categoryId}");
				if (empty($category))
				{
					$catResult = DB::ListItems("INSERT INTO t_attribute_categories(attribute_category_name, category_id) VALUES ('$attributeCategory', {$this->categoryId}); SELECT LAST_INSERT_ID() as id; ");
					$attributeCategoryId = $catResult[0]['id'];
				}
				else 
				{
					$attributeCategoryId = $category[0]['id'];
				}
				
				//attributes insert
				foreach ($attributes as $attributeItem)
				{
					$attribute = DB::ListItems("SELECT attribute_id as id FROM t_attributes WHERE attribute_name = '{$attributeItem['label']}' AND attribute_category_id = '{$attributeCategoryId}'");
					if (empty($attribute))
					{
						$attrResult = DB::ListItems("INSERT INTO t_attributes(attribute_name, attribute_category_id) VALUES ('{$attributeItem['label']}', '$attributeCategoryId'); SELECT LAST_INSERT_ID() as id; ");
						$attributeId = $attrResult[0]['id'];
					}
					else
					{
						$attributeId = $attribute[0]['id'];
					}
					
					//product attributes insert
					$productAttribute = DB::ListItems("SELECT product_attribute_id as id FROM t_products_attributes WHERE attribute_id = '$attributeId' AND product_id = {$this->internalId}");
					if (empty($productAttribute))
					{
						if (DB::ExecuteSQL("
							INSERT INTO t_products_attributes (attribute_id, product_id, product_attribute_value) 
							VALUES ($attributeId, {$this->internalId}, '{$attributeItem['value']}'); 
						") === true)
						{
//							$this->Log(true);
							$result['success']++;
						}	
						else 
						{
							$this->Log(false);
							$result['fail']++;
						}
					}
					else
					{
						if (DB::ExecuteSQL("
							UPDATE t_products_attributes 
							SET 
								attribute_id = $attributeId, 
								product_id = {$this->internalId}, 
								product_attribute_value = '{$attributeItem['value']}'
							WHERE
								product_attribute_id = {$productAttribute[0]['id']}
						") === true)
						{
//							$this->Log(true);
							$result['success']++;
						}	
						else 
						{
							$this->Log(false);
							$result['fail']++;
						}
					}
					
				}
				
			}
			
			return $result;
		}		
		
		/**
		 * Saves product URL into database
		 *
		 * @param string $url url
		 * @param string $source source
		 * 
		 * @return boolean
		 * 
		 */
		public function SaveURL($url, $category, $source, $sortType)
		{
			if (DB::ExecuteSQL("
				INSERT INTO t_product_urls
				(
					product_url_url,
					product_url_category,
					product_url_source,
					product_url_datetime,
					product_url_sort
					)
				VALUES
				(
					'$url',
					'$category',
					'$source',
					'".date('Y-m-d H:i:s')."',
					'$sortType'
				);

			") === true)
			{
				$this->LogURL($url, $category, $source, true);
				$result = true;
			}	
			else 
			{
				$this->LogURL($url, $category, $source, false);
				$result = false;
			}	

			return $result;
		}
		
		/**
		 * Saves images into DB
		 *
		 * @param ProductItem $productItem
		 */
		private function SaveImages()
		{
			foreach ($this->images as $key => $image)
			{
				$imageInfo = pathinfo($image);
				
				DB::ExecuteSQL("
					INSERT INTO t_product_images
					(
						product_id,
						product_image_url
					)
					VALUES
					(
						$this->id,
						'{$key}.{$imageInfo['extension']}'
					);
				");					
			}
		}
		
		/**
		 * Gets product list from DB
		 *
		 * @param int $offset
		 * @param int $number
		 */
		public function GetList($offset, $number)
		{
			//limit
			if (($offset == '') && ($number == ''))
			{
				$limit = '';
			}
			else 
			{
				$offset = ($offset == '') ? 0 : $offset;
				$number = ($number == '') ? 1000000 : $number;
				$limit = "LIMIT $offset, $number";
			}
			
			$products = DB::ListItems("
				SELECT * FROM t_products $limit;
			");	

			return $products;
		}


		/* LOGGERS */
		
		/**
		 * Creates log entry for the inserted product
		 * 
		 * @param boolean $success result
		 *
		 */
		private function Log($success)
		{
			$color = ($success) ? 'green' : 'red';

			echo "<span style = 'color: $color; '>Id: $this->id</span><br />";			
		}

		/**
		 * Creates log entry for the inserted product URL
		 *
		 * @param string $url url
		 * @param string $category category
		 * @param string $source source
		 * @param boolean $success result
		 */
		private function LogURL($url, $category, $source, $success)
		{
			$color = ($success) ? 'green' : 'red';
			
			echo "<span style = 'color: $color; '>
			URL: $url | Category: $category | Source: $source
			</span><br />";
		}
		
	}

?>